package com.smart.home.multi;

import com.smart.home.netty.handler.AbstractChannelInboundHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 模拟客户端1
 *
 * @author zhangpeng
 * @version 1.0
 * @date 2017-03-22
 */
public class VirtualClient1 {

    private String host = "192.168.0.241";
    private int port1 = 4196;

    private void run() {
        //请求处理
        EventLoopGroup group = GroupFactory.getInstance();
        Client1Handler handler = new Client1Handler();
        send(group,port1,handler);
        System.out.println("处理port1");
    /*    Client2Handler handler2 = new Client2Handler();
        send(group,port2,handler2);
        System.out.println("处理port2");*/
      /*  Runnable work2 = new Runnable() {
            Client1Handler handler = new Client1Handler();
            @Override
            public void run() {
                send(group,port2,handler);
            }
        };*/
    }

    private void send(EventLoopGroup group, int port, final AbstractChannelInboundHandler handler) {
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(handler);
                        }
                    });
            ChannelFuture future = bootstrap.connect(host, port);
        } catch (Exception e) {
            System.out.println("服务端请求错误");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        VirtualClient1 client1 = new VirtualClient1();
        client1.run();
    }
}
